//
//  Settings_VC.m
//  WorldOfFacts_V2
//
//  Created by Demjanko Denis on 14.11.12.
//  Copyright (c) 2012 it-dimension. All rights reserved.
//

#import "Settings_VC.h"
#import "SDImageCache.h"
#import "UIImageView+WebCache.h"
#import "UserManager.h"
#import "UIImageExtras.h"

@implementation Settings_VC

#define kOAuthConsumerKey				@"Fs8336VLdsSn4sCHECpA"		//REPLACE With Twitter App OAuth Key  
#define kOAuthConsumerSecret			@"27ELaMssGAFqKReCuXvz8tiIpepBI9FlCPkXqrA"		//REPLACE With Twitter App OAuth Secret

#pragma mark - init

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
    }
    return self;
}

- (void)setNavTitle:(NSString *)title
{
    UILabel *titleView = (UILabel *)self.navigationItem.titleView;
    if (!titleView) {
        titleView = [[UILabel alloc] initWithFrame:CGRectZero];
        titleView.backgroundColor = [UIColor clearColor];
        titleView.font = [UIFont boldSystemFontOfSize:20.0];
        titleView.shadowColor = [UIColor colorWithWhite:0.0 alpha:0.5];
        
        titleView.textColor = [UIColor colorWithRed:187.0f/255.0f green:187.0f/255.0f blue:187.0f/255.0f alpha:1.0f]; // Change to desired color
        
        self.navigationItem.titleView = titleView;
    }
    
    titleView.text = title;
    [titleView sizeToFit];
}

#pragma mark - View Life

- (void)viewDidLoad{
    [super viewDidLoad];
    [self setNavTitle:@"Настройки"];
    
    vkontakte = [Vkontakte sharedInstance];
    vkontakte.delegate = self;
    
    facebook = [[Facebook alloc] initWithAppId:@"235245486548884" andDelegate:self];        
    if ([[NSUserDefaults standardUserDefaults]  objectForKey:@"FBAccessTokenKey"] && [[NSUserDefaults standardUserDefaults]  objectForKey:@"FBExpirationDateKey"]) {
        facebook.accessToken = [[NSUserDefaults standardUserDefaults] objectForKey:@"FBAccessTokenKey"];
        facebook.expirationDate = [[NSUserDefaults standardUserDefaults] objectForKey:@"FBExpirationDateKey"];
    }
    
    
    if(!twitter){  
        twitter = [[SA_OAuthTwitterEngine alloc] initOAuthWithDelegate:self];  
        twitter.consumerKey    = kOAuthConsumerKey;  
        twitter.consumerSecret = kOAuthConsumerSecret;  
    }  
        
    [self addScroller];
    [self addBoxes];
}

-(void)addScroller{
    scroller = [[MGScrollView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    scroller.alwaysBounceVertical = YES;
    scroller.delegate = self;
    [self.view addSubview:scroller];
}

-(void)addBoxes{
    //header 1    
    MGStyledBox *box_1 = [MGStyledBox box];
    box_1.tag = 1;
    
    MGBoxLine *header_box_1 = [MGBoxLine multilineWithText:@"Контролируйте загрузку изображений" font:[UIFont fontWithName:@"HelveticaNeue-Bold" size:16] padding:24.0f];
    [box_1.topLines addObject:header_box_1];
    
    UISwitch *save_images_toogle = [[UISwitch alloc] initWithFrame:CGRectZero];
    save_images_toogle.on = [[NSUserDefaults standardUserDefaults] boolForKey:@"isSave"];
    [save_images_toogle addTarget:self action:@selector(onSaveImages) forControlEvents:UIControlEventValueChanged];
    
    MGBoxLine *line_box_1 = [MGBoxLine lineWithLeft:@"Сохранять изображения?" right:save_images_toogle];
    [box_1.topLines addObject:line_box_1];

    UIButton *delete_button = [UIButton buttonWithType:UIButtonTypeCustom];
    [delete_button setFrame:CGRectMake(0, 0, 89, 30)];
    [delete_button setBackgroundImage:[UIImage imageNamed:@"delet_button_red"] forState:UIControlStateNormal];
    [delete_button addTarget:self action:@selector(onDeleteImages) forControlEvents:UIControlEventTouchUpInside];
    
    MGBoxLine *line_box_2 = [MGBoxLine lineWithLeft:[NSString stringWithFormat:@"Cчитаю..."] right:nil];
    line_box_2.tag = 11;
    [box_1.topLines addObject:line_box_2];
    
    [scroller.boxes addObject:box_1];
    
    if ([[UserManager currentUser] auth]==0){
        [self addLoginBox];
    }
    else{
        [self addLogoutBox];
    }

    [scroller drawBoxesWithSpeed:0.6f];
    [scroller flashScrollIndicators];
    
    [self performSelectorInBackground:@selector(calculate_size) withObject:nil];
}

-(void)addLogoutBox{
    if(scroller.boxes.count==2)
        [scroller.boxes removeObjectAtIndex:1];
    
    MGStyledBox *box = [MGStyledBox box];
    
    MGBoxLine *header_box = [MGBoxLine multilineWithText:@"Учетная запись необходима для отправки комментариев" font:[UIFont fontWithName:@"HelveticaNeue-Bold" size:16] padding:24.0f];
    [box.topLines addObject:header_box];
    
    UIView *left_view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 180, 35)];
    
    UIImageView *avatar_view = [[UIImageView alloc] initWithFrame:CGRectMake(0, 1, 32, 32)];
    
    [avatar_view setImageWithURL:[[UserManager currentUser] ava] placeholderImage:[UIImage imageNamed:@"empty_avatar"] isScaled:YES size:CGSizeMake(100, 100)];
    
    UILabel *name_label = [[UILabel alloc] initWithFrame:CGRectMake(40, 0, 140, 35)];
    name_label.backgroundColor = [UIColor clearColor];
    name_label.font = [UIFont systemFontOfSize:15.0f];
    name_label.text = [[UserManager currentUser] name];
    
    [left_view addSubview:name_label];
    [left_view addSubview:avatar_view];
    
    UIButton *logout_button = [UIButton buttonWithType:UIButtonTypeCustom];
    [logout_button setFrame:CGRectMake(0, 0, 89, 30)];
    [logout_button setBackgroundImage:[UIImage imageNamed:@"logout_btn"] forState:UIControlStateNormal];
    [logout_button addTarget:self action:@selector(onLogout) forControlEvents:UIControlEventTouchUpInside];
    
    MGBoxLine *line_box = [MGBoxLine lineWithLeft:left_view right:logout_button];
    line_box.tag = 12;
    [box.topLines addObject:line_box];
    
    [scroller.boxes addObject:box];
    
    [scroller drawBoxesWithSpeed:0.0f];
    [scroller flashScrollIndicators];
}

-(void)addLoginBox{
    if(scroller.boxes.count==2)
        [scroller.boxes removeObjectAtIndex:1];
    
    MGStyledBox *box = [MGStyledBox box];

    MGBoxLine *header_box = [MGBoxLine multilineWithText:@"Учетная запись необходима для отправки комментариев" font:[UIFont fontWithName:@"HelveticaNeue-Bold" size:16] padding:24.0f];
    [box.topLines addObject:header_box];
    
    UIView *login_view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 130, 35)];
    
    UIButton *tw_button = [UIButton buttonWithType:UIButtonTypeCustom];
    [tw_button setFrame:CGRectMake(5, 0, 35, 35)];
    [tw_button setBackgroundImage:[UIImage imageNamed:@"tw-btn"] forState:UIControlStateNormal];
    [tw_button addTarget:self action:@selector(onTWLogin) forControlEvents:UIControlEventTouchUpInside];
    [login_view addSubview:tw_button];
    
    UIButton *vk_button = [UIButton buttonWithType:UIButtonTypeCustom];
    [vk_button setFrame:CGRectMake(50, 0, 35, 35)];
    [vk_button setBackgroundImage:[UIImage imageNamed:@"vk-icon-login"] forState:UIControlStateNormal];
    [vk_button addTarget:self action:@selector(onVKLogin) forControlEvents:UIControlEventTouchUpInside];
    [login_view addSubview:vk_button];
    
    UIButton *fb_button = [UIButton buttonWithType:UIButtonTypeCustom];
    [fb_button setFrame:CGRectMake(95, 0, 35, 35)];
    [fb_button setBackgroundImage:[UIImage imageNamed:@"facebook-icon-login"] forState:UIControlStateNormal];
    [fb_button addTarget:self action:@selector(onFBLogin) forControlEvents:UIControlEventTouchUpInside];
    [login_view addSubview:fb_button];
    
    
    MGBoxLine *line_box = [MGBoxLine lineWithLeft:@"Войти с помощью..." right:login_view];
    line_box.tag = 12;
    [box.topLines addObject:line_box];
    
    [scroller.boxes addObject:box];
    
    [scroller drawBoxesWithSpeed:0.0f];
    [scroller flashScrollIndicators];
}

-(void)calculate_size{
    [NSThread sleepForTimeInterval:2.0f];
    
    int size = [[SDImageCache sharedImageCache] getSize];
    size = size/1024/1024;
    
    MGStyledBox *box = (MGStyledBox*)[scroller viewWithTag:1];
    
    MGBoxLine *line_box = (MGBoxLine*)[box viewWithTag:11];
    [line_box removeFromSuperview];
    line_box = nil;    
    
    UIButton *delete_button = [UIButton buttonWithType:UIButtonTypeCustom];
    [delete_button setFrame:CGRectMake(0, 0, 89, 30)];
    [delete_button setBackgroundImage:[UIImage imageNamed:@"delet_button_red"] forState:UIControlStateNormal];
    [delete_button addTarget:self action:@selector(onDeleteImages) forControlEvents:UIControlEventTouchUpInside];
    
    line_box = [MGBoxLine lineWithLeft:[NSString stringWithFormat:@"Загружено %d МБ.",size] right:delete_button];
    line_box.tag = 11;
    [box.topLines replaceObjectAtIndex:2 withObject:line_box];
    
    [scroller drawBoxesWithSpeed:0.0f];
    [scroller flashScrollIndicators];
}

#pragma mark - IBactions

-(void)onSaveImages{
    BOOL isSave = ![[NSUserDefaults standardUserDefaults] boolForKey:@"isSave"];
    
    [[NSUserDefaults standardUserDefaults] setBool:isSave forKey:@"isSave"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

-(void)onDeleteImages{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Внимание" message:@"Вы действительно хотите удалить все загруженные изображения?" delegate:self cancelButtonTitle:@"Отмена" otherButtonTitles:@"Удалить", nil];
    [alert show];
}

#pragma mark - UIAlertView delegate

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if(buttonIndex==1){
        [self showHud];
        [self performSelector:@selector(deleteImages) withObject:nil afterDelay:1.0f];
    }
}

#pragma mark - delete

-(void)deleteImages{
    [[SDImageCache sharedImageCache] clearDisk];

    MGStyledBox *box = (MGStyledBox*)[scroller viewWithTag:1];

    MGBoxLine *line_box = (MGBoxLine*)[box viewWithTag:11];
    [line_box removeFromSuperview];
    line_box = nil;    
    
    UIButton *delete_button = [UIButton buttonWithType:UIButtonTypeCustom];
    [delete_button setFrame:CGRectMake(0, 0, 89, 30)];
    [delete_button setBackgroundImage:[UIImage imageNamed:@"delet_button_red"] forState:UIControlStateNormal];
    [delete_button addTarget:self action:@selector(onDeleteImages) forControlEvents:UIControlEventTouchUpInside];
    
    line_box = [MGBoxLine lineWithLeft:[NSString stringWithFormat:@"Загружено %d МБ.",0] right:delete_button];
    line_box.tag = 11;
    [box.topLines replaceObjectAtIndex:2 withObject:line_box];
    
    [scroller drawBoxesWithSpeed:0.0f];
    [scroller flashScrollIndicators];

    [self removeHud];
}

#pragma mark - logout

-(void)onLogout{
    [self showHud];
    if([vkontakte isAuthorized])
        [vkontakte performSelector:@selector(logout) withObject:nil afterDelay:0.5f];
    else if([twitter isAuthorized])
        [self onTWLogin];
    else
        [facebook logout:self];
}

#pragma mark - login

-(void)loginToTW{
    UIViewController *controller = [SA_OAuthTwitterController controllerToEnterCredentialsWithTwitterEngine:twitter delegate:self];  
    if (controller)
        [self presentModalViewController: controller animated: YES];
}

-(void)onTWLogin{
    if(![twitter isAuthorized]){  
        [self performSelector:@selector(loginToTW) withObject:nil afterDelay:0.2f];  
    } 
    else{
        NSMutableDictionary *info = [NSMutableDictionary dictionary];
        [info setValue:@"0" forKey:@"auth"];
        [[UserManager currentUser] setUser:info];
        
        NSHTTPCookie *cookie;
        NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
        for (cookie in [storage cookies]) {
            [storage deleteCookie:cookie];
        }
        [[NSUserDefaults standardUserDefaults] synchronize];
        
        [self performSelector:@selector(removeHud) withObject:nil afterDelay:0.5f];
        
        [twitter clearAccessToken];
        
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"authData"];
        [[NSUserDefaults standardUserDefaults] synchronize];
        
        [self addLoginBox];
    }
}

-(void)onFBLogin{    
    if (![facebook isSessionValid]) 
        [facebook authorize:[NSArray arrayWithObjects:@"publish_stream",@"publish_actions",@"offline_access",nil]];
    else if([vkontakte isAuthorized] && [[UserManager currentUser] auth]==0){
        [self showHud];
        
        double delayInSeconds = 2.0;
        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
            [facebook requestWithGraphPath:@"me/" andDelegate:self];
        });
    }
    else{
        [facebook logout:self];
    }
}

-(void)onVKLogin{
    if (![vkontakte isAuthorized]) 
        [vkontakte authenticate];
    else if([vkontakte isAuthorized] && [[UserManager currentUser] auth]==0){
        [self showHud];
        
        double delayInSeconds = 2.0;
        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
            [vkontakte getUserInfo];
        });
    }
    else
        [vkontakte logout];
}

#pragma mark - VkontakteDelegate

- (void)vkontakteDidFailedWithError:(NSError *)error{
    [self dismissModalViewControllerAnimated:YES];
}

- (void)showVkontakteAuthController:(UIViewController *)controller{
    [self presentModalViewController:controller animated:YES];
}

- (void)vkontakteAuthControllerDidCancelled{
    [self dismissModalViewControllerAnimated:YES];
}

- (void)vkontakteDidFinishLogin:(Vkontakte *)_vkontakte{
    [self dismissModalViewControllerAnimated:YES];
    [self showHud];
    [vkontakte getUserInfo];
}

- (void)vkontakteDidFinishLogOut:(Vkontakte *)_vkontakte{
    [self removeHud];
    
    NSMutableDictionary *info = [NSMutableDictionary dictionary];
    [info setValue:@"0" forKey:@"auth"];
    [[UserManager currentUser] setUser:info];
    
    [self addLoginBox];
}

- (void)vkontakteDidFinishGettinUserInfo:(NSDictionary *)info{
    [self removeHud];    
    
    [info setValue:@"2" forKey:@"auth"];
   
    [[UserManager currentUser] setUser:info];
    
    [self addLogoutBox];
}


#pragma mark Facebook

-(void)loginToFacebook{    
    if (![facebook isSessionValid]) 
        [facebook authorize:[NSArray arrayWithObjects:@"publish_stream",@"publish_actions",@"offline_access",nil]];
    else
        [facebook logout:self];
}

- (void)fbDidLogin{    
    [self showHud];
    
    [[NSUserDefaults standardUserDefaults] setObject:facebook.accessToken forKey:@"FBAccessTokenKey"];
    [[NSUserDefaults standardUserDefaults] setObject:facebook.expirationDate forKey:@"FBExpirationDateKey"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
    [facebook requestWithGraphPath:@"me/" andDelegate:self];
}

- (void)fbDidLogout{
    [self removeHud];
    
    NSMutableDictionary *info = [NSMutableDictionary dictionary];
    [info setValue:@"0" forKey:@"auth"];
    [[UserManager currentUser] setUser:info];
    
    [self addLoginBox];
}

- (void)request:(FBRequest *)request didFailWithError:(NSError *)error{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Facebook" message:[error localizedDescription] delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [alert show];
    
    [self removeHud];
}

- (void)request:(FBRequest *)request didLoad:(id)result{    
    NSMutableDictionary *info = [NSMutableDictionary dictionaryWithDictionary:result];
    [info setValue:@"1" forKey:@"auth"];
    [[UserManager currentUser] setUser:info];
    
    [self removeHud];
    
    [self addLogoutBox];
}

#pragma mark - Twitter


- (void) OAuthTwitterController: (SA_OAuthTwitterController *) controller authenticatedWithUsername: (NSString *) username {    
    [self showHud];
    
    [twitter getUserInformationFor:username];
}

- (void) storeCachedTwitterOAuthData: (NSString *) data forUsername: (NSString *) username {    
	[[NSUserDefaults standardUserDefaults] setObject: data forKey: @"authData"];
	[[NSUserDefaults standardUserDefaults] synchronize];
}

- (NSString *) cachedTwitterOAuthDataForUsername: (NSString *) username {
	return [[NSUserDefaults standardUserDefaults] objectForKey: @"authData"];
}

- (void) requestSucceeded: (NSString *) requestIdentifier {
}

- (void)userInfoReceived:(NSArray *)userInfo forRequest:(NSString *)connectionIdentifier{
    [self removeHud];

    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setValue:@"4" forKey:@"auth"];
    [dict setValue:[[userInfo objectAtIndex:0]valueForKey:@"screen_name"] forKey:@"name"];
    [dict setValue:[[userInfo objectAtIndex:0]valueForKey:@"profile_image_url"] forKey:@"profile_image_url"];

    [[UserManager currentUser] setUser:dict];
    
    [self addLogoutBox];
}

- (void) requestFailed: (NSString *) requestIdentifier withError: (NSError *) error {    
    [self removeHud];
        
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Ошибка" message:error.localizedDescription delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [alert show];
}

#pragma mark - HUD

-(void)showHud{
    hud = [[MBProgressHUD alloc] initWithView:self.navigationController.view];
    [self.navigationController.view addSubview:hud];
    hud.dimBackground = YES;
    [hud show:YES];
}

-(void)removeHud{
    [hud hide:YES];
    [hud removeFromSuperview];
    hud = nil; 
}

#pragma mark - Memory Management

- (void)didReceiveMemoryWarning{
    [super didReceiveMemoryWarning];
}

-(void)dealloc{
    scroller = nil;
    hud = nil;
}

@end
